import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable, from, switchMap } from 'rxjs'

@Injectable()
export class ResponseSerializerInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    if (context.getType() !== 'http') {
      return next.handle()
    }

    return next.handle().pipe( // switchMap to ensure that the response is serialized before returning
      switchMap((value) =>
        from(
          Promise.resolve({
            ok: true,
            result: value,
            service: process.env.BOTICORD_SERVICE ?? 'unknown',
          }),
        ),
      ),
    )
  }
}
